package com.rankeiot.core.util;

import org.springframework.context.ApplicationContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AbstractLocaleResolver;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class LocaleUtil {
    private static ApplicationContext context;
    public LocaleUtil(ApplicationContext ctx){
        context=ctx;
    }
    public static void setDefaultLocal(Locale local){
        AbstractLocaleResolver localeResolver=(AbstractLocaleResolver)context.getBean(LocaleResolver.class);
        localeResolver.setDefaultLocale(local);
    }
    /**
     * 获取i18n/messages语言包中相关信息
     * @param message
     * @param args
     * @return
     */
    public static String get(String message,Object ...args){
        try {
            return  context.getMessage(message, args, LocaleContextHolder.getLocale());
        }catch (Exception e){
            return message;
        }
    }

    /**
     * 编码语言字符串
     * @param zh
     * @param en
     * @return {zh:zh,en:en}
     */
    public static String encode(String zh,String en){
       if(StringUtil.isEmpty(zh)){
           return en;
       }
       if(StringUtil.isEmpty(en)){
           return zh;
       }
       Map<String,String> langMap=new HashMap<>();
       langMap.put("zh",zh);
       langMap.put("en",en);
       return JSONUtil.toJSONString(langMap);
    }
    public static Locale getLocale(){
        return LocaleContextHolder.getLocale();
    }
    /**
     * 解码语言字符串
     * @param langStr
     * @return
     */
    public static String d(String langStr){
        return d(langStr,LocaleContextHolder.getLocale());
    }
    public static String d(String langStr,Locale locale){
        if(StringUtil.isEmpty(langStr)){
            return langStr;
        }
        if(langStr.startsWith("{")&&langStr.endsWith("}")){
            Map<String,String> langMap=JSONUtil.parseObject(langStr);
            if(langMap.size()==0){
                return "";
            }
            String lang=locale.getLanguage();
            String real=langMap.get(lang);
            if(real!=null){
                return real;
            }
            return langMap.values().iterator().next();
        }
        return langStr;
    }
    /**
     * 自动选择语言
     * @param zh
     * @param en
     * @return
     */
    public static String t(String zh,String en){
        return t(zh,en,LocaleContextHolder.getLocale());
    }
    public static String t(String zh, String en, Locale locale){
       if(Locale.CHINESE.equals(locale)){
           return zh;
       }else{
           if(StringUtil.isEmpty(en)){
               return zh;
           }
           return en;
       }
    }
}
